<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="设备设施管理"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
      :search-info="searchInfo"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddFacilityButtonClick">新增</a-button>
        <a-button @click="onImportFacilityButtonClick">批量导入</a-button>
        <a-button danger @click="onDeleteFacilityButtonClick">批量删除</a-button>
      </template>
      <template #unitid="{ record }">
        {{ treeToList(unitOption).find((item) => item.unitid == record.unitid)?.unitname }}
      </template>

      <template #name="{ record }">
        {{ record.name }}
        <a-popover placement="rightTop">
          <template #content>
            <QrCode
              :value="'/pages/facility/facilityInfo?id=' + record.id"
              width="120"
              ref="qrRef"
            />
            <a-button @click="download(record)" block size="small">下载</a-button>
          </template>
          <QrcodeOutlined style="font-size: 16px; color: #0960bd" />
        </a-popover>
      </template>
      <template #status="{ record }">
        <a-tag v-if="record.status == 1" color="green">在用</a-tag>
        <a-tag v-else color="red">停用</a-tag>
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditFacilityButtonClick.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>
    <ImportFacilityModal
      :unitOption="unitOption"
      @register="registerImportFacilityModal"
      @success="afterSuccess"
    />
    <AddOrUpdateFacility
      :unitOption="unitOption"
      @register="registerAddOrUpdateFacilityModal"
      @success="afterSuccess"
    />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onBeforeMount, onMounted, ref, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { deleteFacility, getFacilityList, importFacility } from '/@/api/ehs/facility';
  import { facilityTableColumns, facilityConditionSchema } from './facility.data';
  import { QrcodeOutlined } from '@ant-design/icons-vue';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import ImportFacilityModal from './ImportFacilityModal.vue';
  import AddOrUpdateFacility from './AddOrUpdateFacility.vue';
  import { queryUnitDivision } from '/@/api/ehs/unitDivision';
  import { Modal } from 'ant-design-vue';
  import { QrCode, QrCodeActionType } from '/@/components/Qrcode/index';
  export default defineComponent({
    name: 'organizationIndex',
    components: {
      BasicTable,
      TableAction,
      Tag,
      ImportFacilityModal,
      AddOrUpdateFacility,
      QrcodeOutlined,
      QrCode,
    },
    setup() {
      const searchInfo = ref({
        orgcode: '',
      });
      const unitOption = ref([]);
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const qrRef = ref<Nullable<QrCodeActionType>>(null);
      const [registerImportFacilityModal, { openModal: openImportFacilityModal }] = useModal();
      const [registerAddOrUpdateFacilityModal, { openModal: openAddOrUpdateFacilityModal }] =
        useModal();
      const [registerTable, { reload, getSelectRowKeys, getForm }] = useTable({
        api: getFacilityList,
        columns: facilityTableColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        ellipsis: true,
        immediate: false,
        indexColumnProps: {
          width: 50,
        },
        afterFetch: (data) => {
          return data ?? [];
        },
        clickToRowSelect: true,
        useSearchForm: true,
        formConfig: {
          schemas: facilityConditionSchema,
          labelWidth: 100, //设置查询表单中label的宽度
        },
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
      });

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      /**
       * 单元二维码下载
       */
      function download(record) {
        const qrEl = unref(qrRef);
        if (!qrEl) return;
        qrEl.download(record.name);
      }

      /**
       * 打开导入窗口
       */

      function onImportFacilityButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '设备管理',
          operateString: '导入',
          orgcode: searchInfo.value.orgcode,
        };
        openImportFacilityModal(true, propsData);
      }

      function onAddFacilityButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '设备设施管理',
          operateType: OperationTypeEnum.ADD,
        };
        openAddOrUpdateFacilityModal(true, propsData);
      }

      function onEditFacilityButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '设备设施管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
        };
        openAddOrUpdateFacilityModal(true, propsData);
      }

      function onDeleteFacilityButtonClick() {
        if (getSelectRowKeys().length < 1) {
          createMessage.error('请选择要删除的设备。', 2);
          return;
        }
        Modal.confirm({
          title: '是否确认删除?',
          onOk() {
            deleteFacility(getSelectRowKeys().join(','))
              .then((res) => {
                console.log('res', res);
                //res判断结果：同时==undefined和null
                if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                  createMessage.success('删除成功。', 2);
                  afterSuccess();
                }
              })
              .catch((ex) => {
                console.log('catch ', ex);
              });
          },
          onCancel() {
            return;
          },
        });
      }

      /**
       * @description:将树形结构转换为列表结构
       */
      function treeToList(arr) {
        let res = []; // 用于存储递归结果（扁平数据）
        // 递归函数
        let fn = (source) => {
          source?.forEach((el) => {
            res.push(el);
            el.children && el.children.length > 0 ? fn(el.children) : ''; // 子级递归
          });
        };
        fn(arr);
        return res;
      }

      onMounted(() => {
        getUserOrganization(projectCode.value).then((res) => {
          searchInfo.value.orgcode = res.orgcode;
          queryUnitDivision({
            includechilds: true,
            isdept: false,
            flagisvalid: false,
            orgcode: res.orgcode,
          }).then((res) => {
            unitOption.value = res;
            getForm().updateSchema({
              field: 'unitid',
              componentProps: {
                getPopupContainer: (triggerNode) => document.body,
                treeData: unitOption.value,
                fieldNames: { label: 'unitname', value: 'unitid', children: 'children' },
                listHeight: 150,
                treeDefaultExpandAll: true, //默认展开
                showCheckedStrategy: 'SHOW_ALL', //定义选中项回填的方式:默认只显示子节点;SHOW_ALL:显示所有选中节点(包括父节点);SHOW_PARENT:只显示父节点(当父节点下所有子节点都选中时).
              },
            });
          });
          reload();
        });
      });
      return {
        treeToList,
        unitOption,
        searchInfo,
        registerImportFacilityModal,
        registerAddOrUpdateFacilityModal,
        registerTable,
        afterSuccess,
        onImportFacilityButtonClick,
        onDeleteFacilityButtonClick,
        onAddFacilityButtonClick,
        onEditFacilityButtonClick,
        download,
        qrRef,
      };
    },
  });
</script>

<style scoped></style>
